package com.chaoshi.common;

import com.google.common.util.concurrent.RateLimiter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class RateLimitAspect {

    @Around("@annotation(rateLimit)")
    public Object around(ProceedingJoinPoint joinPoint, RateLimit rateLimit) throws Throwable {
        RateLimiter limiter = RateLimiter.create(rateLimit.permitsPerSecond());
        if (rateLimit.timeout() <= 0) {
            limiter.acquire();
            return joinPoint.proceed();
        }

        if (limiter.tryAcquire(rateLimit.timeout(), TimeUnit.MILLISECONDS)) {
            return joinPoint.proceed();
        }
        throw new RuntimeException("请求过于频繁，请稍后再试");
    }
}
